package net.sxnic.ugr.menu.util;

import java.io.File;
import java.io.IOException;
import java.util.List;

import net.sxnic.comm.CommConstant;
import net.sxnic.ugr.menu.Menu;
import net.sxnic.ugr.menu.MenuManager;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MenuImportUtils {

	private static final Logger log = LoggerFactory
			.getLogger(MenuImportUtils.class);

	/**
	 * 初始化菜单表。清空数据之后重新插入
	 * 
	 * @param menuManager
	 * @param file
	 * @throws IOException
	 */
	public static void importMenu(MenuManager menuManager, File file)
			throws IOException {
		// String filePath = "src/etc/menu.txt";
		// File dataFile = new File(filePath);
		List<String> lines = FileUtils.readLines(file, "utf-8");

		// log.debug("clear table data.............");
		//
		// menuManager.clear();

		log.debug("init menu start...........");

		int size = lines.size();
		importMenu(menuManager, (String[]) lines.toArray(new String[size]));

		log.debug("init menu over............");
	}

	/**
	 * 菜单表导入。清空数据之后重新插入
	 * 
	 * @param menuManager
	 * @param data
	 * @throws IOException
	 */
	public static void importMenu(MenuManager menuManager, String data)
			throws IOException {
		String[] lines = StringUtils.split(data, '\n');

		log.debug("clear table data.............");

		menuManager.clear();

		log.debug("init menu start...........");

		importMenu(menuManager, lines);

		log.debug("init menu over............");
	}

	/**
	 * 菜单表导入。清空数据之后重新插入
	 * 
	 * @param menuManager
	 * @param lines
	 */
	public static void importMenu(MenuManager menuManager, String[] lines) {

		for (String line : lines) {

			if (StringUtils.isBlank(line)
					|| line.contains(CommConstant.TXT_IGNORE_CHARS)) {
				continue;
			}

			String[] m = line.split(",");

			// 根据code，查询表中是否有此code的菜单信息，如果有则update，否则create

			Menu menu = menuManager.findByUnique("code", m[0].trim());

			if (menu != null) {

				menu.setCode(m[0].trim());
				menu.setValue(m[1].trim());
				menu.setUrl(m[2].trim());
				menu.setMenuOrder(Integer.parseInt(m[3].trim()));
				menu.setImageurl(m[4].trim());

				menuManager.update(menu);				
			}else{
				menu = new Menu();
				menu.setCode(m[0].trim());
				menu.setValue(m[1].trim());
				menu.setUrl(m[2].trim());
				menu.setMenuOrder(Integer.parseInt(m[3].trim()));
				menu.setImageurl(m[4].trim());
				menuManager.save(menu);
			}

			log.debug("====update menu success. code ===" + menu.getCode());
		}
	}
}
